package com.tbit.uqbike.tergateway.mtpkg;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.annotation.JSONField;
import com.tbit.uqbike.protocol.AnalyzeImpl.AProtocol;
import com.tbit.uqbike.tergateway.data.TerGatewayData;
import com.tbit.uqbike.tergateway.entity.AConnInfo;
import com.tbit.uqbike.tergateway.entity.RemoteControl;
import com.tbit.uqbike.util.StringUtil;
import io.netty.buffer.ByteBuf;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;

/**
 * @author MyWin E-mail:335918956@qq.com
 * @version 1.0
 * @createTime 2019/2/20 0020 10:49
 */
public class MtControl extends MtBasePkg {
    private static Logger logger = LoggerFactory.getLogger(MtControl.class);

    public static class Cmd {
        @JSONField(name = "命令ID")
        public String cmdId;
        public List<CmdContent> content;

        public String getKvStr() {
            if (content != null && !content.isEmpty()) {
                if (content.get(0).result != null) {
                    if (content.get(0).result.data != null) {
                        if (content.get(0).result.data.params != null && !content.get(0).result.data.params.isEmpty()) {
                            return String.format("%s=%s", content.get(0).result.data.params.get(0).key, content.get(0).result.data.params.get(0).value);
                        }
                    } else {
                        return String.format("code=%d", content.get(0).result.code);
                    }
                }
            }
            return "";
        }
    }

    public static class CmdParam {
        public String key;
        public Object value;
    }

    public static class CmdData {
        public List<CmdParam> params;
    }

    public static class CmdResult {
        public int code;
        public CmdData data;
    }

    public static class CmdContent {
        public String c;
        public CmdResult result;
    }

    @JSONField(name = "中控id")
    public String sn;
    @JSONField(name = "指令详情")
    public Cmd cmd;


    @Override
    public void doBusiness() {
        logger.info(JSONObject.toJSONString(this));
        if (null == cmd || cmd.cmdId == null) {
            return;
        }
        Object obj = null;
        // 先根据流水号来
        if (!StringUtil.IsNullOrEmpty(cmd.cmdId)) {
            obj = TerGatewayData.getStrSerNoMap(cmd.cmdId);
        }
        if (null != obj) {
            if (obj instanceof RemoteControl) {
                RemoteControl remoteControl = (RemoteControl) obj;
                remoteControl.buildTerKvRsp(cmd.getKvStr());
            }
        }
    }

    @Override
    public boolean autoRsp() {
        return false;
    }

    @Override
    public ByteBuf getRsp(AConnInfo conn, AProtocol protocol) {
        return null;
    }
}
